<template>
    <BPTable ref='tableRef' align='center' row-key='id' :columns='columns' :api='pageApi' :buttons='buttons' :rowSelection="false">
        <template #fields="{ record }">
                <div :class="$style.fieldBoxs">
                    <span v-for="(item, index) in record.fields" :key="index" :class="$style.fieldBox">
                        <span>{{ $t('port') }}{{ index + 1 }}：</span>
                        <template v-for="(field, i) in item" :key="i">
                            <a-tag color="green">{{ i18n.t(field) }}</a-tag>
                        </template>
                    </span>
                </div>
        </template>
    </BPTable>

    <BDialog v-model:visible='visible' :title='dialogTitle' width='600px' :confirm='submit' @close="resetForm">
        <a-form ref='formRef' layout="vertical" :rules="rules" :label-col='{span : 5}' :model='formData'>
            <a-form-item style='display:none' name='id'>
                <a-input type='hidden' v-model:value='formData.id' />
            </a-form-item>
            <a-form-item :label="$c('name')" name="name">
                <a-input v-model:value='formData.name' />
            </a-form-item>
            <template v-for="(v, i) in formData.ports" :key="i">
                <a-form-item :label="$c('port') + ':' + (i + 1)" :name="['ports', i]" :rules="[{required : true, message : $c('please', 'select', 'field')}]">
                    <div :class="$style.portRow">
                        <a-select :class="$style.input" v-model:value='formData.ports[i]' :options="fieldOptions" mode="multiple"></a-select>
                        <MinusCircleOutlined v-if="formData.ports.length > 1 " :class="$style.minus" @click="delPort(i)" />
                    </div>
                </a-form-item>
            </template>
            <a-form-item>
                <a-button type="dashed" @click="addPort"><PlusOutlined />{{ $c('add', 'port') }}</a-button>
            </a-form-item>
            <a-form-item :label="$c('remark')" name="remark">
                <a-input v-model:value='formData.remark' />
            </a-form-item>
        </a-form>
    </BDialog>

</template>

<script lang='ts' setup>
    import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
    import { optionsApi } from '@/api/devices/DeviceDataField'
    import { pageApi, deleteApi, saveApi } from '@/api/devices/PortModel'
    import { useI18nStore } from '@/store/i18n'
    import { message, Modal } from 'ant-design-vue'
    import { ref } from 'vue'
    import { Rule } from 'ant-design-vue/lib/form';



    

    const i18n = useI18nStore()
    const visible = ref(false)

    const tableRef = ref()
    const formRef = ref()
    const dialogTitle = ref()
    

    const formData = ref<{ports : number[][]; [key:string]:any}>({
        id : 0,
        name : '',
        ports : [],
        remark : '',
    })

    function delPort(i:number) {
        Modal.confirm({
            title : i18n.t('confirmDel', ['']),
            onOk() {
                formData.value.ports.splice(i, 1)
            }
        })
    }

    function addPort() {
        getFieldOptions()
        formData.value.ports.push([])
    }

    const fieldOptions = ref<{value:number;label:string}[]>([])

    function getFieldOptions() {
        if(fieldOptions.value.length == 0) {
            optionsApi().then(res => {
                res.data.forEach(row => {
                    fieldOptions.value.push({value : row.id, label : i18n.t(row.name)})
                })
            })
        }
        
    }
    
    const rules: Record<string, Rule[]> = {
        name : [
            {
                required : true,
                message : i18n.concat('please', 'input', 'name')
            }
        ]
    };

    

    const buttons = ref<SearchButton[]>([])
    buttons.value.push({
        button : 'add',
        func : () => {
            dialogTitle.value = i18n.t('add')
            formData.value.ports.splice(0)
            addPort()
            visible.value = true
        }
    })


  
    function resetForm() {
        formRef.value.clearValidate()
        formRef.value.resetFields()
    }
    
    async function submit() {
        let { id, ...params} = await formRef.value.validate()
        
        if(id) {
            params.id = Number(id)
        }

        

        const res = await saveApi(params)
        if(res.success) {
            resetForm()
            visible.value = false
            message.success(i18n.t('saveSuccess'))
            tableRef.value.load()
        }else {
            Modal.error({
                title : res.msg
            })
        }
    }


    

    const columns = ref<Column[]>([
        {
            title : i18n.t('name'),
            dataIndex : 'name',
            align : 'center',
           
            translate : true,
            inSearch : true
        },

        {
            title : i18n.concat('port', 'number'),
            dataIndex : 'count',
            align : 'center',
            
            inSearch : true,
        },

        {
            title : i18n.concat('port', 'field'),
            dataIndex : 'fields',
            align : 'center'
        },

        {
            title : i18n.t('remark'),
            dataIndex : 'remark',
           
            align : 'center',
        },

        {
            title : i18n.t('action'),
            dataIndex : '$action',
            align : 'center',
           
            $edit : (row) => {
                dialogTitle.value = i18n.t('edit')
                getFieldOptions()
                for(let k in formData.value) {
                    formData.value[k] = row[k]
                    
                }
                // formFields.forEach(field => {
                //     if(field.name == 'expireIn') {
                //         field.defaultValue = row[field.name] ? dayjs(row[field.name] * 1000) : ''
                //     }else {
                //         field.defaultValue = row[field.name]
                //     }
                    
                // })

                visible.value = true
            },

            $delete :  async (row) => {
                const res = await deleteApi(row.id)
                if(res.success) {
                    message.success(i18n.t('deleteSuccess'))
                    tableRef.value.load()
                }else {
                    message.error(res.msg)
                }
            }
        }
    ])


    

    
</script>

<style lang='scss' module>
    .portRow{
        display: flex;
        align-items: center;

        .input{
            flex: 1;
        }
        .minus{
            margin-left: 10px;
            color: #999;
            cursor: pointer;
            font-size: 24px;
        }
    }

    .fieldBoxs{
        display: inline-block;
        text-align: left;
        max-width: 500px;
        .fieldBox{
            display: inline-block;
            padding: 5px;
        }
    }
</style>